package com.powernode.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.config.AliyunDxConfig;
import com.powernode.constant.MemberConstants;
import com.powernode.domain.Member;
import com.powernode.ex.handler.BusinessException;
import com.powernode.mapper.MemberMapper;
import com.powernode.service.SendService;
import com.powernode.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

@Service
public class SendServiceImpl implements SendService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AliyunDxConfig aliyunDxConfig;

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 发送短信验证码
     *
     * @param map
     */
    @Override
    public void sendPhoneMsg(Map<String, Object> map) {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()

                .setAccessKeyId(System.getenv(aliyunDxConfig.getAccessKeyID()))
                .setAccessKeySecret(System.getenv(aliyunDxConfig.getAccessKeySecret()));
        config.endpoint = aliyunDxConfig.getEndpoint();
        try {
            com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);
            String phonenum = (String) map.get("phonenum");
            //生成一个随机数字
            String randomNumber = RandomUtil.randomNumbers(4);
            //将生成的随机数存放到redis中
            stringRedisTemplate.opsForValue().set(MemberConstants.MSG_PHONE_PREFIX + phonenum, randomNumber, Duration.ofMinutes(30));
            //创建模板参数
            String templateParam = "{\"code\":\"+randomNumber+\"}";
            //创建发送短信请求
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(phonenum)
                    .setSignName(aliyunDxConfig.getSignName())
                    .setTemplateCode(aliyunDxConfig.getTemplateCode())
                    .setTemplateParam(templateParam);
            client.sendSmsWithOptions(sendSmsRequest, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 保存手机号码
     *
     * @param map
     * @return
     */
    @Override
    public Boolean saveMsgPhone(Map<String, Object> map) {
        //获取会员输入的短信验证码
        String code = (String) map.get("code");
        //获取会员手机号码
        String phonenum = (String) map.get("phonenum");
        //从redis中获取当前手机号码对应的短信验证码
        String redisCode = stringRedisTemplate.opsForValue().get(MemberConstants.MSG_PHONE_PREFIX + phonenum);
        //判断短信验证码是否正确
        if (!code.equals(redisCode)) {
            throw new BusinessException("请输入正确的短信验证码");
        }
        //将会员手机号码更新到会员信息中
        Member member = new Member();
        member.setUserMobile(phonenum);
        //获取当前会员的openId
        String openId = AuthUtils.getMemberOpenId();
        return memberMapper.update(member, new LambdaQueryWrapper<Member>()
                .eq(Member::getOpenId, openId)) > 0;
    }
}
